﻿using Learun.Util;
using Learun.Util.SqlSugar;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;

namespace Learun.Application.TwoDevelopment.ZZDT_EC
{
    /// <summary>
    /// 版 本 PIT-ADMS V7.0.3 敏捷开发框架
    /// Copyright (c) 2013-2018 Hexagon PPM
    /// 创 建：超级管理员
    /// 日 期：2022-02-24 11:10
    /// 描 述：对象类型
    /// </summary>
    public class ec_objecttypeService
    {
        #region 仓储
        Repository<ec_projectEntity> _projectRepository => new Repository<ec_projectEntity>();
        Repository<ec_objecttypeEntity> _objecttypeRepository => new Repository<ec_objecttypeEntity>();
        #endregion
        #region 获取数据
        /// <summary>
        /// 获取列表数据
        /// <summary>
        /// <returns></returns>
        public IEnumerable<ec_objecttypeEntity> GetTree(string queryJson)
        {
            try
            {
                //参考写法
                var queryParam = queryJson.ToJObject();
                var ProjectId = queryParam["ProjectId"].ToString();

                var ObjectTypeName = queryParam["ObjectTypeName"].ToString();
                var TagNumber = queryParam["TagNumber"].ToString();

                var tableName = ProjectSugar.TableName<ec_objecttypeEntity>(ProjectId);
                var enginedataTableName = ProjectSugar.TableName<ec_enginedataEntity>(ProjectId);
                var listAll = _objecttypeRepository.AsQueryable().AS(tableName).ToList();
                var list = _objecttypeRepository.AsQueryable().AS(tableName)
                    .WhereIF(!string.IsNullOrEmpty(ObjectTypeName), a => a.ObjectTypeName.Contains(ObjectTypeName))
                    .LeftJoin<ec_enginedataEntity>((a, b) => a.ObjectTypeID == b.ObjectTypeID).AS<ec_enginedataEntity>(enginedataTableName)
                    .WhereIF(!string.IsNullOrEmpty(TagNumber), (a, b) => b.TagNumber.Contains(TagNumber))
                    .Distinct().Select(a => a).OrderBy(a => a.OrderID).ToList();

                if (!string.IsNullOrEmpty(TagNumber))
                {
                    var listAdded =new  List<ec_objecttypeEntity>();
                    //想办法把上级的节点也带出来，因为位号只是在最末端的objecttype上，这样导致出来的就不是一颗树了
                    foreach (var objectType in list)
                    {
                        var parentTypes = objectType.FullPath.Replace($",{objectType.ObjectTypeID}", "").Split(',');
                        foreach (var parentTypeId in parentTypes)
                        {
                            if (!listAdded.Any(x=>x.ObjectTypeID == parentTypeId))
                            {
                               var parent= listAll.First(x => x.ObjectTypeID == parentTypeId);
                                if (parent != null)
                                {
                                    listAdded.Add(parent);
                                }
                            }
                        }
                    }

                    list.AddRange(listAdded);
                }
                return list;
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }
        /// <summary>
        /// 获取列表数据
        /// <summary>
        /// <returns></returns>
        public IEnumerable<ec_objecttypeEntity> GetListByProjectId(string queryJson)
        {
            try
            {
                //参考写法
                var queryParam = queryJson.ToJObject();
                ////按项目取表名公用方法
                var tableName = ProjectSugar.TableName<ec_objecttypeEntity>(queryParam["ProjectId"].ToString());
                //数据插入
                var objecttype = new ec_objecttypeEntity();
                objecttype.Create();
                SqlSugarHelper.Db.Insertable<ec_objecttypeEntity>(objecttype).AS(tableName).ExecuteCommand();
                //查询数据
                var list = SqlSugarHelper.Db.Queryable<ec_objecttypeEntity>().AS(tableName).ToList();

                return list;
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }
        /// <summary>
        /// 获取实体数据
        /// <param name="keyValue">主键</param>
        /// <summary>
        /// <returns></returns>
        public ec_objecttypeEntity GetEntity(string keyValue, string ProjectId)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(ProjectId))
                {
                    return _objecttypeRepository.GetById(keyValue);
                }
                else
                {
                    var ProjectEntity = _projectRepository.GetById(ProjectId);
                    var strSql = new StringBuilder();
                    strSql.Append($@"SELECT * FROM ec_objecttype_{ProjectEntity.ProjectIndex} WHERE ObjectTypeID = @ObjectTypeID ");
                    //List<ec_objecttypeEntity> list = this.BaseRepository().FindList<ec_objecttypeEntity>(strSql.ToString(), new { ObjectTypeID = keyValue }).ToList();
                    //return list.FirstOrDefault();
                    return SqlSugarHelper.Db.Ado.SqlQuerySingle<ec_objecttypeEntity>(strSql.ToString(), new { ObjectTypeID = keyValue });
                }
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }

        #endregion

        #region 提交数据

        /// <summary>
        /// 删除实体数据
        /// <param name="keyValue">主键</param>
        /// <summary>
        /// <returns></returns>
        public void DeleteEntity(string keyValue, string ProjectId)
        {
            SqlSugarHelper.Db.BeginTran();
            try
            {
                if (string.IsNullOrWhiteSpace(ProjectId))
                {
                    //对象类型删除时，删除子目录和目录下的记录。
                    SqlSugarHelper.Db.Ado.ExecuteCommand($" DELETE FROM ec_objecttypep WHERE ObjectTypeID IN (SELECT DISTINCT ST1.ObjectTypeID FROM ec_objecttype ST1 WHERE FIND_IN_SET('{keyValue}',ST1.FullPath)); ");
                    _objecttypeRepository.Delete(t => t.FullPath.Contains(keyValue));
                }
                else
                {
                    var ProjectEntity = _projectRepository.GetById(ProjectId);
                    //对象类型删除时，删除子目录和目录下的记录。
                    SqlSugarHelper.Db.Ado.ExecuteCommand($@" DELETE FROM ec_objecttypep_{ProjectEntity.ProjectIndex} WHERE ObjectTypeID IN (SELECT DISTINCT ST1.ObjectTypeID FROM ec_objecttype_{ProjectEntity.ProjectIndex} ST1 WHERE FIND_IN_SET('{keyValue}',ST1.FullPath)); 
                                        DELETE FROM ec_objecttype_{ProjectEntity.ProjectIndex} WHERE FullPath LIKE '%{keyValue}%'; ");
                }
                SqlSugarHelper.Db.CommitTran();
            }
            catch (Exception ex)
            {
                SqlSugarHelper.Db.RollbackTran();
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }
        #endregion

    }
}
